%%% @author LinZhengJian <linzhj@35info.cn>
%%% @copyright (C) 2012, LinZhengJian
%%% @doc
%%%
%%% @end
%%% Created :  3 Aug 2012 by LinZhengJian <linzhj@35info.cn>

-module(heyjude_database).

-include("heyjude_database.hrl").

-define(SCHEMADIR, "schema").
-define(DATADIR, "data").

-export([start/0]).

start()->
    Nodes = [node()],
    ok = ensure_mnesia(),
    ok = create_schema(Nodes),
    ok = start_mnesia(),
    ok = create_sys_tables(Nodes),
    schema_script:run(Nodes),
    ok.

ensure_mnesia()->
    stopped = mnesia:stop(),
    ok.

create_schema(Nodes)->
    case mnesia:create_schema(Nodes) of
	ok->
	    ok;
	{error,{_,{already_exists,_}}} ->
	    ok;
	Other ->
	    {error, Other}
    end.

start_mnesia()->
    mnesia:start().

create_sys_tables(Nodes)->
    case heyjude_database_utility:is_table_exists(?SYS_TABLE_SCRIPT_LOG) of
	false->
	    {atomic, ok} = mnesia:create_table(?SYS_TABLE_SCRIPT_LOG, [{disc_only_copies, Nodes}, 
					       {attributes, record_info(fields, ?SYS_TABLE_SCRIPT_LOG)}]),
	    ok;
	true->
	    ok
    end,
    ok.    
